<template>
  <!-- 角色管理 -->
  <div class="module_par">
    <div class="module_con">
      <!-- 搜索区域 -->
      <div class="search_box">
        <el-row :gutter="20" class="box_center">
          <el-col>
            <span class="searchTxt">角色名称:</span>
            <el-input v-model="searchBox.name" autocomplete="off" size="small" class="searchInp"></el-input>
            <el-button type="primary" class="searchBtn" @click="goSearch()" size="small" v-if="$requestBtnApi.role.queryBtn">查询</el-button>
            <el-button type="primary" class="searchBtn reditBtn" @click="redit()" size="small">重置</el-button>
            <el-button type="primary" class="searchBtn reditBtn" @click="addData()" size="small" v-if="this.$requestBtnApi.role.addBtn">新增</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- 主体内容 -->
      <div class="table-content">
        <el-table :data="tableData" border tooltip-effect="dark" style="width: 100%">
          <el-table-column type="index" align="center" label="#"></el-table-column>
          <el-table-column prop="roleName" align="center" label="角色名称"></el-table-column>
          <el-table-column prop="roleAlias" align="center" label="角色别名"></el-table-column>
          <el-table-column prop="tenantName" align="center" label="所属租户"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
          <el-table-column prop="updateTime" align="center" label="修改时间"></el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <!-- <a class="table_a" @click="addData(scope.row)"><i class="el-icon-circle-plus-outline"></i>新 增</a> -->
              <a class="table_a table_a_left" @click="grantUser(scope.row)" v-if="$requestBtnApi.role.grantBtn">
                <i class="el-icon-setting"></i>授 权
              </a>
              <a class="table_a table_a_left" @click="editData(scope.row)" v-if="$requestBtnApi.role.editBtn">
                <i class="el-icon-edit"></i>编 辑
              </a>
              <a class="table_a table_a_left table_a_del" @click="delData(scope.row)" v-if="$requestBtnApi.role.delBtn">
                <i class="el-icon-delete"></i>删 除
              </a>
            </template>
          </el-table-column>
        </el-table>
        <div class="pageBox">
        <el-pagination v-show="total>0" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 420]" :page-size="tableQuery.limit" layout="total, sizes, prev, pager, next, jumper"
          :total="total"></el-pagination></div>
        <!-- <el-table
          :data="tableData"
          border
          tooltip-effect="dark"
          style="width: 100%"
          row-key="id"
          highlight-current-row
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column type="index" align="center" label="#"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleAlias" align="center" label="角色别名"></el-table-column>
          <el-table-column prop="tenantName" align="center" label="所属租户"></el-table-column>
          <el-table-column prop="createUser" align="center" label="创建者"></el-table-column>
          <el-table-column prop="createTime" align="center" label="创建时间"></el-table-column>
          <el-table-column prop="updateUser" align="center" label="修改者"></el-table-column>
          <el-table-column prop="updateTime" align="center" label="修改时间"></el-table-column>
          <el-table-column
            align="center"
            width="230"
            label="操作">
            <template slot-scope="scope">
              <a class="table_a" @click="addData(scope.row)"><i class="el-icon-circle-plus-outline"></i>新 增</a>
              <a class="table_a table_a_left" @click="grantUser(scope.row)"><i class="el-icon-setting"></i>授 权</a>
              <a class="table_a table_a_left" @click="editData(scope.row)"><i class="el-icon-edit"></i>编 辑</a>
              <a class="table_a table_a_left  table_a_del" @click="delData(scope.row)"><i class="el-icon-delete"></i>删 除</a>
            </template>
          </el-table-column>
        </el-table>-->
      </div>
      <!-- 编辑 -->
      <el-dialog title="角色编辑" :visible.sync="dialogEditSta">
        <el-form :model="editList" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色名称:">
                <el-input v-model="editList.name" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色别名">
                <el-input v-model="editList.roleAlias" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="租户">
                <el-select v-model="editList.tent" placeholder="请选择" size="small" disabled>
                  <el-option v-for="item in editList.optionTent" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogEditSta = false" size="small">取 消</el-button>
          <el-button type="primary" @click="editYes" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 新增 -->
      <el-dialog title="角色新增" :visible.sync="dialogAddSta">
        <el-form :model="addList" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色名称">
                <el-input v-model="addList.name" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色别名">
                <el-input v-model="addList.roleAlias" autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租户">
                <el-select v-model="addList.tent" placeholder="请选择" size="small">
                  <el-option v-for="item in addList.optionTent" :key="item.value" :label="item.label" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddSta = false" size="small">取 消</el-button>
          <el-button type="primary" @click="addYes" size="small">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 详情 -->
      <el-dialog title="详情" :visible.sync="dialogSeeSta">
        <el-form :model="seeDataList" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色名称:">
                <el-input v-model="seeDataList.name" disabled autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租户">
                <el-select v-model="seeDataList.user" disabled placeholder="暂无">
                  <el-option v-for="item in seeDataList.option" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色别名">
                <el-input v-model="seeDataList.roleAlias" disabled autocomplete="off" size="small" class="searchInp"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSeeSta = false" size="small">取 消</el-button>
        </div>
      </el-dialog>
      <!-- 授权 -->
      <el-dialog title="授权" :visible.sync="dialogGrantSta" custom-class="grant_dia">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="菜单权限" name="first">
            <el-tree ref="grantTree" :data="menuPerm" show-checkbox node-key="id" :props="defaultProps"></el-tree>
          </el-tab-pane>
          <!--<el-tab-pane label="数据权限" name="second">
            <el-tree ref="organ" :data="organList" show-checkbox node-key="id" :props="defaultProps2"></el-tree>
          </el-tab-pane>-->
          <!--<el-tab-pane label="接口权限" name="third">
            <el-tree ref="interface" :data="interfaceList" node-key="id" :props="defaultProps3"></el-tree>
          </el-tab-pane>-->
        </el-tabs>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogGrantSta = false" size="small">取 消</el-button>
          <el-button type="primary" @click="getCheckedNodes" size="small">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 按钮权限控制
        permissionList: {
          cx: true,
          xz: true,
          bj: true,
          qx: true,
          xq: true,
        },
        // 搜索区域值
        searchBox: {
          name: "",
        }, // 搜索内容
        tableData: [], // table数据
        total: 0,
        tableQuery: {
          limit: 5,
          indexNo: 0,
        },
        dialogEditSta: false, // 编辑弹框判断
        // 编辑弹框数据
        editList: {
          id: "",
          name: "",
          roleAlias: "",
          optionTent: [],
          tent: "",
        }, // 编辑弹框数据
        // 搜索状态
        searchSta: false,
        // 新增弹框 状态
        dialogAddSta: false,
        // 新增子  父级数据
        addDataList: null,
        // 新增弹框数据
        addList: {
          name: "",
          path: "",
          roleAlias: "",
          optionTent: [],
          tent: "",
        },
        // 编辑 数据
        dataList: {},
        // 编辑弹框状态
        dialogSeeSta: false,
        // 编辑弹框数据
        seeDataList: {
          name: "",
          roleAlias: "",
          user: "",
          option: [],
        },
        dialogGrantSta: false,
        activeName: "first",
        menuPerm: [],
        menuPermOption: [],
        organOption: [],
        apiOption: [],
        defaultProps: {
          children: "children",
          label: "permName",
        },
        defaultProps2: {
          children: "children",
          label: "name",
        },
        defaultProps3: {
          children: "children",
          label: "apiName",
        },
        organList: null,
        interfaceList: null,
        roleId: "",
      };
    },
    methods: {
      handleSizeChange(val) {
        console.log(val);
        this.tableQuery.limit = val;
        this.tableQuery.indexNo = 0;
        this.getTableList();
      },
      handleCurrentChange(val) {
        this.tableQuery.indexNo = val - 0 - 1;
        this.getTableList();
      },
      handleClick(val) {
        console.log(val.name);
        if (val.name == "third") {
          this.$alert(
            "接口权限功能开发中。此功能将在下一版本中开放使用",
            "友情提示", {
              confirmButtonText: "确定",
              callback: (action) => {},
            }
          );
        }
      },
      // 授权  弹框确定
      getCheckedNodes() {
        const grantGetCheckedNodes = this.$refs.grantTree.getCheckedNodes();
        const grantGetHalfCheckedNodes = this.$refs.grantTree.getHalfCheckedNodes();
        //const organGetCheckedNodes = this.$refs.organ.getCheckedNodes();
        // const organGetHalfCheckedNodes = this.$refs.organ.getHalfCheckedNodes();
        //const interfaceGetCheckedNodes = this.$refs.interface.getCheckedNodes();
        //const interfaceGetHalfCheckedNodes = this.$refs.interface.getHalfCheckedNodes();
        // 菜单权限全选 半选id
        const grantId = grantGetCheckedNodes.map((v) => {
          return v.id;
        });
        const grantId2 = grantGetHalfCheckedNodes.map((v) => {
          return v.id;
        });
        // 数据权限  全选  半选id
        //const organId = organGetCheckedNodes.map((v) => {
        //  return v.id;
        //});
        // const organId2 = organGetHalfCheckedNodes.map((v) => {
        //   return v.id;
        // });
        // 接口权限  全选 半选id
        // const interfaceId = interfaceGetCheckedNodes.map((v) => {
        //   return v.id;
        // });
        // const interfaceId2 = interfaceGetHalfCheckedNodes.map((v) => {
        //   return v.id;
        // });
        const data = {
          roleId: this.roleId,
          menuPermList: [...grantId, ...grantId2],
          dataPermList: [],
          apiPermList: [],
          // apiPermList: [...interfaceId, ...interfaceId2],
        };
        this.$requestA[this.$requestBtnApi.role.grantType](
          this.$requestBtnApi.role.grantUrl,
          data,
          (res) => {
            if (res.code == "200") {
              this.$message.success("授权成功");
              this.dialogGrantSta = false;
            }
          }
        );
      },
      // 授权按钮
      grantUser(val) {
        this.roleId = val.id;
        console.log(val);
        this.activeName = "first";
        this.getMenuGrant(val);
        // this.getRolePerm();
        // this.dialogGrantSta = true;
        // this.$nextTick(() => {
        //   this.$refs.grantTree.setCheckedNodes(s);
        //   // this.$refs.organ.setCheckedKeys([]);
        //   // this.$refs.interface.setCheckedKeys([]);
        // });
      },
      // 回显菜单   数据  接口
      getRolePerm() {
        console.log(typeof null);
        console.log(typeof []);
        this.menuPermOption = [];
        this.organOption = [];
        this.apiOption = [];
        this.$requestA.get("/IAM/role/" + this.roleId, {}, (res) => {
          const menuPerm = res.data.menuPerm;
          const dataPerm = res.data.dataPerm;
          const apiPerm = res.data.apiPerm;
          this.dialogGrantSta = true;
          var me = this.getRecursion(menuPerm, this.menuPerm);
          // var da = this.getRecursion2(dataPerm, this.organList);
          // var ap = this.getRecursion3(apiPerm, this.interfaceList);
          this.$nextTick(() => {
            this.$refs.grantTree.setCheckedNodes([]);
            this.$refs.grantTree.setCheckedNodes(me);
            this.$refs.organ.setCheckedNodes([]);
            this.$refs.organ.setCheckedNodes(dataPerm);
            // this.$refs.interface.setCheckedNodes([]);
            // this.$refs.interface.setCheckedNodes(ap);
          });
        });
      },
      // 菜单权限
      getRecursion(list, parList) {
        for (const key1 in list) {
          for (const key2 in parList) {
            if (list[key1].id == parList[key2].id) {
              if (list[key1].children) {
                this.getRecursion(list[key1].children, parList[key2].children);
              } else {
                this.menuPermOption.push(list[key1]);
              }
            }
          }
        }
        return this.menuPermOption;
      },
      // 数据权限
      getRecursion2(list, parList) {
        for (const key1 in list) {
          for (const key2 in parList) {
            if (list[key1].id == parList[key2].id) {
              if (list[key1].children.length) {
                this.getRecursion2(list[key1].children, parList[key2].children);
              } else {
                this.organOption.push(list[key1]);
              }
            }
          }
        }
        return this.organOption;
      },
      // 接口权限
      getRecursion3(list, parList) {
        for (const key1 in list) {
          for (const key2 in parList) {
            if (list[key1].id == parList[key2].id) {
              if (list[key1].children) {
                this.getRecursion3(list[key1].children, parList[key2].children);
              } else {
                this.apiOption.push(list[key1]);
              }
            }
          }
        }
        return this.apiOption;
      },
      // 删除table数据
      delData(val) {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then(() => {
            this.$requestA[this.$requestBtnApi.role.delType](
              this.$requestBtnApi.role.delUrl + "/" + val.id, {},
              (res) => {
                if (res.code == "200") {
                  this.$message.success("删除成功");
                }
                this.getTableList();
              }
            );
          })
          .catch(() => {});
      },
      // 查看详情
      seeData(data) {
        this.seeDataList = {
          name: "",
          roleAlias: "",
          user: "",
          option: [],
        };
        this.seeDataList.name = data.roleName;
        this.seeDataList.roleAlias = data.roleAlias;
        this.seeDataList.user = data.tenantCode;
        this.dialogSeeSta = true;
        // this.getSeeDataList(data.id)
      },
      // 新增按钮
      addData(val) {
        if (val) {
          this.addDataList = val;
        } else {
          this.addDataList = null;
        }
        this.addList.name = "";
        this.addList.path = "";
        this.addList.roleAlias = "";
        this.addList.tent = null;
        this.dialogAddSta = true;
      },
      // 重置
      redit() {
        this.tableQuery.limit = 5;
        this.tableQuery.indexNo = 0;
        this.searchBox.name = "";
        this.searchSta = false;
        this.getTableList();
      },
      // 搜索
      goSearch() {
        this.tableQuery.limit = 5;
        this.tableQuery.indexNo = 0;
        this.searchSta = true;
        this.getTableList();
      },
      // 新增确定
      addYes() {
        if (this.addList.name.trim() == "") {
          this.$message.error("请输入角色名称");
          return false;
        }
        if (!this.addList.tent) {
          this.$message.error("请选择租户");
          return false;
        }
        const data = {
          roleName: this.addList.name,
          roleAlias: this.addList.roleAlias,
          tenantCode: this.addList.tent.value,
          tenantName: this.addList.tent.label,
          parentId: this.addDataList ? this.addDataList.id : 0,
        };
        this.$requestA[this.$requestBtnApi.role.addType](
          this.$requestBtnApi.role.addUrl,
          data,
          (res) => {
            this.dialogAddSta = false;
            this.getTableList();
            if (res.code == "200") {
              this.$message.success("操作成功");
            }
          }
        );
      },
      // 编辑确定
      editYes() {
        if (this.editList.name.trim() == "") {
          this.$message.error("请输入角色名称");
          return false;
        }
        const data = this.dataList;
        data.roleName = this.editList.name;
        data.tenantCode = this.editList.tent;
        data.roleAlias = this.editList.roleAlias;
        this.$requestA[this.$requestBtnApi.role.editType](
          this.$requestBtnApi.role.editUrl,
          data,
          (res) => {
            this.dialogEditSta = false;
            this.getTableList();
            if (res.code == "200") {
              this.$message.success("操作成功");
            }
          }
        );
      },
      // 编辑按钮
      editData(data) {
        this.dataList = data;
        this.editList.id = data.id;
        this.editList.roleAlias = data.roleAlias;
        this.editList.name = data.roleName;
        this.editList.tent = data.tenantCode;
        this.dialogEditSta = true;
      },
      //   获取table数据
      getTableList() {
        const data = {
          loginCode: localStorage.getItem("loginCode"),
          tenantCode: localStorage.getItem("TENANT_CODE"),
          roleName: this.searchSta ? this.searchBox.name : "",
          size: this.tableQuery.limit,
          page: this.tableQuery.indexNo,
        };
        this.$requestA[this.$requestBtnApi.role.queryType](
          this.$requestBtnApi.role.queryUrl,
          data,
          (res) => {
            console.log(res);
            this.tableData = res.data.content;
            this.total = res.data.totalElements;
          }
        );
      },
      // 获取当前所有租户
      getAllZh() {
        this.addList.optionTent = [];
        this.editList.optionTent = [];
        this.$requestA.get(
          "/IAM/tenant/queryTenant", {
            tenantCode: localStorage.getItem("TENANT_CODE")
          },
          (res) => {
            for (const key in res.data) {
              this.addList.optionTent.push({
                value: res.data[key].tenantCode,
                label: res.data[key].tenantName,
              });
              this.editList.optionTent.push({
                value: res.data[key].tenantCode,
                label: res.data[key].tenantName,
              });
              this.seeDataList.option.push({
                value: res.data[key].tenantCode,
                label: res.data[key].tenantName,
              });
            }
          }
        );
      },
      // 获取菜单权限
      getMenuGrant(val) {
        const data = {
          loginCode: localStorage.getItem("loginCode"),
          permType: "1",
        };
        this.$requestA.get("/IAM/permission/tree", data, (res) => {
          this.menuPerm = res.data;
          this.getOrgan(val);
        });
      },
      // 获取数据权限
      getOrgan(val) {
        const data = {
          tenantCode: val.tenantCode,
        };
        this.$requestA.get("/IAM/organ/dataPrem", data, (res) => {
          this.organList = res.data;
          this.getInterface();
        });
      },
      // 获取接口权限
      getInterface() {
        this.$requestA.get("/IAM/interface", {
          permType: "2"
        }, (res) => {
          this.interfaceList = res.data;
          this.getRolePerm();
        });
      },
    },
    created() {
      this.$route.meta.menuList.map((item) => {
        console.log(item);
        if (item.eleName == "查询") {
          this.$requestBtnApi.role.queryUrl = item.eleUrl;
          this.$requestBtnApi.role.queryType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.role.queryBtn = true;
        } else if (item.eleName == "新增") {
          this.$requestBtnApi.role.addUrl = item.eleUrl;
          this.$requestBtnApi.role.addType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.role.addBtn = true;
        } else if (item.eleName == "编辑") {
          this.$requestBtnApi.role.editUrl = item.eleUrl;
          this.$requestBtnApi.role.editType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.role.editBtn = true;
        } else if (item.eleName == "删除") {
          this.$requestBtnApi.role.delUrl = item.eleUrl;
          this.$requestBtnApi.role.delType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.role.delBtn = true;
        } else if (item.eleName == "授权") {
          this.$requestBtnApi.role.grantUrl = item.eleUrl;
          this.$requestBtnApi.role.grantType =
            item.operType == "delete" ? "dele" : item.operType;
          this.$requestBtnApi.role.grantBtn = true;
        }
      });
      // this.getMenuGrant();
      this.getAllZh();
      this.getTableList();
      // this.getOrgan();
      // this.getInterface();
    },
  };
</script>
<style>
  .grant_dia {
    width: 30% !important;
  }

  .grant_dia .el-tabs__content {
    min-height: 50vh;
    max-height: 50vh;
    overflow-y: scroll;
  }

  /*修改滚动条样式*/
  .grant_dia .el-tabs__content::-webkit-scrollbar {
    width: 6px;
    height: 100%;
  }

  .grant_dia .el-tabs__content::-webkit-scrollbar-track {
    background: rgb(239, 239, 239);
    border-radius: 2px;
  }

  .grant_dia .el-tabs__content::-webkit-scrollbar-thumb {
    background: #bfbfbf;
    border-radius: 10px;
  }

  .grant_dia .el-tabs__content::-webkit-scrollbar-thumb:hover {
    background: #333;
  }

  .grant_dia .el-tabs__content::-webkit-scrollbar-corner {
    background: #179a16;
  }
</style>
<style scoped>
  @import "../../assets/css/base.css";

  .search_box {
    background: #fff;
    border-radius: 5px;
    padding: 40px 40px 60px 40px;
    margin: 0 0 20px 0;
  }

  .pageBox {
    display: flex;
    width: 100%;
    justify-content: left;
    margin-top: 10px;
  }

  .box_center {
    text-align: left;
  }

  .searchBtn {
    margin-left: 80px;
  }

  .reditBtn {
    margin-left: 20px;
  }
</style>
